#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
画布组件 - 用于图像显示和标注
"""

import cv2
import numpy as np
from PyQt5.QtWidgets import (
    QGraphicsView, QGraphicsScene, QGraphicsItem,
    QGraphicsPixmapItem, QGraphicsRectItem, QGraphicsPolygonItem,
    QGraphicsLineItem, QGraphicsEllipseItem, QGraphicsPathItem,
    QApplication
)
from PyQt5.QtGui import (
    QPixmap, QImage, QPen, QColor, QBrush, QPolygonF, QTransform,
    QPainter, QCursor
)
from PyQt5.QtCore import Qt, QRectF, pyqtSignal, QSizeF, QEvent, QPointF
import math

from core.utils.segment import SmartSegmentation

class ImageCanvas(QGraphicsView):
    """图像显示与标注画布"""
    
    # 自定义信号
    zoom_changed = pyqtSignal(float)  # 缩放比例改变信号
    selection_changed = pyqtSignal(QRectF)  # 选择区域改变信号
    annotation_added = pyqtSignal(dict)  # 添加标注信号
    annotation_deleted = pyqtSignal(int)  # 删除标注信号
    annotation_selected = pyqtSignal(int)  # 选择标注信号
    image_loaded = pyqtSignal(bool)  # 图像加载信号
    annotation_changed = pyqtSignal()  # 标注变更信号
    
    def __init__(self, parent=None):
        """
        初始化画布
        
        Args:
            parent (QWidget, optional): 父窗口
        """
        super().__init__(parent)
        
        # 初始化场景
        self.scene = QGraphicsScene(self)
        self.setScene(self.scene)
        
        # 图像项
        self.image_item = None
        self.image_path = None  # 添加图像路径属性
        
        # 当前工具类型
        self.current_tool = "select"
        
        # 当前标签类别
        self.current_class = ""
        
        # 当前标注颜色
        self.current_color = QColor(Qt.red)
        
        # 缩放级别
        self.zoom_factor = 1.0
        
        # 鼠标追踪
        self.setMouseTracking(True)
        
        # 设置渲染质量
        self.setRenderHints(
            QPainter.Antialiasing | 
            QPainter.TextAntialiasing | 
            QPainter.SmoothPixmapTransform
        )
        
        # 设置拖动模式
        self.setDragMode(QGraphicsView.ScrollHandDrag)
        
        # 设置缩放模式
        self.setResizeAnchor(QGraphicsView.AnchorUnderMouse)
        self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
        
        # 初始化缓存图像
        self.image = None
        self.original_image = None
        
        # 标注列表
        self.annotations = []
        self.annotation_items = []
        
        # 绘制状态变量
        self.drawing = False
        self.start_point = None
        self.current_item = None
        self.selected_annotation_idx = -1
        
        # ROI区域, 相对坐标(0-1)
        self.roi = QRectF(0.0, 0.0, 1.0, 1.0)  # 默认为整个图像
        self.roi_item = None
        self.roi_visible = False
        
        # 旋转矩形属性
        self.rotation_handle = None  # 旋转矩形的旋转控制点
        self.rotation_line = None  # 旋转控制线
        self.temp_rect = None  # 临时矩形，用于旋转矩形的初始创建
        self.rect_center = None  # 矩形中心点
        self.rotation_angle = 0  # 旋转角度
        
        # 智能分割
        self.segmentation = SmartSegmentation()
        self.segmentation_points = []  # 分割交互点
        self.segmentation_labels = []  # 标签 (1=前景, 0=背景)
    
    def set_image(self, image_path):
        """
        设置显示图像
        
        Args:
            image_path (str): 图像文件路径
        
        Returns:
            bool: 设置是否成功
        """
        try:
            # 保存图像路径
            self.image_path = image_path
            
            # 读取图像
            self.original_image = cv2.imread(image_path)
            if self.original_image is None:
                return False
            
            # BGR转RGB
            self.image = cv2.cvtColor(self.original_image, cv2.COLOR_BGR2RGB)
            
            # 转换为QImage
            height, width, channels = self.image.shape
            bytes_per_line = channels * width
            q_image = QImage(
                self.image.data, 
                width, 
                height, 
                bytes_per_line, 
                QImage.Format_RGB888
            )
            
            # 转换为QPixmap并显示
            pixmap = QPixmap.fromImage(q_image)
            
            # 清除场景
            self.scene.clear()
            self.annotations = []
            self.annotation_items = []
            self.roi_item = None
            
            # 添加图像到场景
            self.image_item = QGraphicsPixmapItem(pixmap)
            self.scene.addItem(self.image_item)
            
            # 重置视图
            self.resetTransform()
            self.setSceneRect(self.image_item.boundingRect())
            self.fitInView(self.image_item, Qt.KeepAspectRatio)
            
            # 计算初始缩放比例
            self.zoom_factor = 1.0
            self.zoom_changed.emit(self.zoom_factor)
            
            # 设置ROI
            self.set_roi(self.roi)
            
            return True
            
        except Exception as e:
            print(f"设置图像失败: {e}")
            return False
    
    def zoom_in(self):
        """放大视图"""
        self.scale(1.2, 1.2)
        self.zoom_factor *= 1.2
        self.zoom_changed.emit(self.zoom_factor)
    
    def zoom_out(self):
        """缩小视图"""
        self.scale(1/1.2, 1/1.2)
        self.zoom_factor /= 1.2
        self.zoom_changed.emit(self.zoom_factor)
    
    def fit_to_view(self):
        """适应视图大小"""
        if self.image_item:
            self.fitInView(self.image_item, Qt.KeepAspectRatio)
            # 重新计算缩放比例
            view_rect = self.viewport().rect()
            scene_rect = self.transform().mapRect(self.image_item.boundingRect())
            self.zoom_factor = min(
                view_rect.width() / scene_rect.width(),
                view_rect.height() / scene_rect.height()
            )
            self.zoom_changed.emit(self.zoom_factor)
    
    def actual_size(self):
        """实际大小"""
        if self.image_item:
            self.resetTransform()
            self.zoom_factor = 1.0
            self.zoom_changed.emit(self.zoom_factor)
    
    def set_tool(self, tool_name):
        """
        设置当前工具
        
        Args:
            tool_name (str): 工具名称
        """
        self.current_tool = tool_name
        
        # 根据工具类型设置鼠标样式和拖动模式
        if tool_name == "select":
            self.setCursor(Qt.ArrowCursor)
            self.setDragMode(QGraphicsView.RubberBandDrag)
        elif tool_name == "pan":
            self.setCursor(Qt.OpenHandCursor)
            self.setDragMode(QGraphicsView.ScrollHandDrag)
        elif tool_name in ["rectangle", "polygon", "rotated_rectangle", "point"]:
            self.setCursor(Qt.CrossCursor)
            self.setDragMode(QGraphicsView.NoDrag)
        elif tool_name == "smart_segment":
            self.setDragMode(QGraphicsView.NoDrag)
            # 设置十字光标
            QApplication.setOverrideCursor(QCursor(Qt.CrossCursor))
            # 清除之前的分割点
            self.segmentation_points = []
            self.segmentation_labels = []
        else:
            self.setCursor(Qt.ArrowCursor)
            self.setDragMode(QGraphicsView.NoDrag)
    
    def wheelEvent(self, event):
        """
        鼠标滚轮事件
        
        Args:
            event (QWheelEvent): 滚轮事件
        """
        if event.modifiers() & Qt.ControlModifier:
            # 根据滚轮方向放大缩小
            if event.angleDelta().y() > 0:
                self.zoom_in()
            else:
                self.zoom_out()
            event.accept()
        else:
            # 默认行为
            super().wheelEvent(event)
    
    def add_rectangle_annotation(self, rect, label, color=Qt.red):
        """
        添加矩形标注
        
        Args:
            rect (QRectF): 矩形区域
            label (str): 标签
            color (QColor): 颜色
        
        Returns:
            QGraphicsRectItem: 创建的矩形项
        """
        # 创建矩形项
        rect_item = QGraphicsRectItem(rect)
        
        # 设置样式
        pen = QPen(color)
        pen.setWidth(2)
        rect_item.setPen(pen)
        
        # 半透明填充
        brush = QBrush(color)
        brush.setStyle(Qt.SolidPattern)
        color_with_alpha = QColor(color)
        color_with_alpha.setAlpha(50)  # 设置透明度
        brush.setColor(color_with_alpha)
        rect_item.setBrush(brush)
        
        # 使项可选择和可移动
        rect_item.setFlag(QGraphicsItem.ItemIsSelectable, True)
        rect_item.setFlag(QGraphicsItem.ItemIsMovable, True)
        
        # 添加到场景
        self.scene.addItem(rect_item)
        
        # 保存标注
        self.annotations.append({
            'type': 'rectangle',
            'item': rect_item,
            'label': label,
            'rect': rect,
            'color': color
        })
        
        return rect_item
    
    def clear_annotations(self):
        """清除所有标注"""
        for anno in self.annotations:
            self.scene.removeItem(anno['item'])
        self.annotations = []
        self.annotation_items = []
    
    def add_polygon_annotation(self, points, label, color=Qt.red):
        """
        添加多边形标注
        
        Args:
            points (list): QPointF点列表
            label (str): 标签
            color (QColor): 颜色
        
        Returns:
            QGraphicsPolygonItem: 创建的多边形项
        """
        from PyQt5.QtGui import QPolygonF
        from PyQt5.QtWidgets import QGraphicsPolygonItem
        
        # 创建多边形
        polygon = QPolygonF(points)
        
        # 创建多边形项
        poly_item = QGraphicsPolygonItem(polygon)
        
        # 设置样式
        pen = QPen(color)
        pen.setWidth(2)
        poly_item.setPen(pen)
        
        # 半透明填充
        brush = QBrush(color)
        brush.setStyle(Qt.SolidPattern)
        color_with_alpha = QColor(color)
        color_with_alpha.setAlpha(50)  # 设置透明度
        brush.setColor(color_with_alpha)
        poly_item.setBrush(brush)
        
        # 添加到场景
        self.scene.addItem(poly_item)
        
        # 保存标注
        self.annotations.append({
            'type': 'polygon',
            'item': poly_item,
            'label': label,
            'points': points
        })
        
        return poly_item
    
    def get_annotations(self):
        """
        获取标注数据
        
        Returns:
            list: 标注数据列表
        """
        result = []
        for anno in self.annotations:
            if anno['type'] == 'rectangle':
                rect = anno['rect']
                result.append({
                    'type': 'rectangle',
                    'x': rect.x(),
                    'y': rect.y(),
                    'width': rect.width(),
                    'height': rect.height(),
                    'label': anno['label'],
                    'color': anno['color'].name() if isinstance(anno['color'], QColor) else anno['color']
                })
            elif anno['type'] == 'polygon':
                points = anno['points']
                # 将QPointF转换为坐标列表
                point_list = [(p.x(), p.y()) for p in points]
                result.append({
                    'type': 'polygon',
                    'points': point_list,
                    'label': anno['label'],
                    'color': anno['color'].name() if isinstance(anno['color'], QColor) else anno['color']
                })
            # 可以添加其他类型的标注处理
        
        return result

    def load_image(self, image_path):
        """
        加载并显示图像
        
        Args:
            image_path (str): 图像文件路径
        
        Returns:
            bool: 加载是否成功
        """
        return self.set_image(image_path)

    def load_annotations(self, annotations):
        """
        加载标注数据
        
        Args:
            annotations (list): 标注数据列表
        """
        # 清除现有标注
        self.clear_annotations()
        
        # 添加新标注
        for anno in annotations:
            anno_type = anno.get("type")
            
            if anno_type == "rectangle":
                x = anno.get("x", 0)
                y = anno.get("y", 0)
                width = anno.get("width", 0)
                height = anno.get("height", 0)
                label = anno.get("label", "")
                color_name = anno.get("color", "#FF0000")
                
                rect = QRectF(x, y, width, height)
                color = QColor(color_name)
                self.add_rectangle_annotation(rect, label, color)
            
            elif anno_type == "polygon":
                points = anno.get("points", [])
                label = anno.get("label", "")
                color_name = anno.get("color", "#FF0000")
                
                # 转换点列表为QPointF列表
                qt_points = [QPointF(p[0], p[1]) for p in points]
                color = QColor(color_name)
                
                # 添加多边形标注
                self.add_polygon_annotation(qt_points, label, color)
            
            # 可以添加其他类型的标注处理

    def set_color(self, color):
        """
        设置当前标注颜色
        
        Args:
            color (QColor): 颜色
        """
        self.current_color = color

    def set_class(self, class_name):
        """
        设置当前标签类别
        
        Args:
            class_name (str): 标签类别名称
        """
        self.current_class = class_name 

    def mousePressEvent(self, event):
        """
        鼠标按下事件
        
        Args:
            event (QMouseEvent): 鼠标事件
        """
        if self.image_item is None:
            return super().mousePressEvent(event)
        
        # 获取场景坐标
        scene_pos = self.mapToScene(event.pos())
        
        # 根据当前工具处理
        if self.current_tool == "select":
            super().mousePressEvent(event)
        
        elif self.current_tool == "rectangle":
            if event.button() == Qt.LeftButton:
                self.drawing = True
                self.start_point = scene_pos
                
                # 创建临时矩形
                pen = QPen(self.current_color, 2, Qt.SolidLine)
                self.current_item = self.scene.addRect(QRectF(scene_pos, QSizeF(0, 0)), pen)
                self.current_item.setZValue(1)  # 确保在图像上方
        
        elif self.current_tool == "polygon":
            if event.button() == Qt.LeftButton:
                if not self.drawing:
                    self.drawing = True
                    self.temp_points = [scene_pos]
                    
                    # 创建临时多边形
                    pen = QPen(self.current_color, 2, Qt.SolidLine)
                    polygon = QPolygonF([scene_pos])
                    self.current_item = self.scene.addPolygon(polygon, pen)
                    self.current_item.setZValue(1)
                else:
                    # 添加新点
                    self.temp_points.append(scene_pos)
                    
                    # 更新多边形
                    pen = QPen(self.current_color, 2, Qt.SolidLine)
                    polygon = QPolygonF(self.temp_points)
                    
                    # 移除旧的多边形并创建新的
                    if self.current_item:
                        self.scene.removeItem(self.current_item)
                    
                    self.current_item = self.scene.addPolygon(polygon, pen)
                    self.current_item.setZValue(1)
            
            elif event.button() == Qt.RightButton and self.drawing:
                # 右键完成多边形
                if len(self.temp_points) >= 3:
                    # 完成多边形
                    self._complete_polygon()
                
                # 重置状态
                self.drawing = False
                self.temp_points = []
                self.current_item = None
        
        elif self.current_tool == "rotated_rectangle":
            if event.button() == Qt.LeftButton:
                if not self.drawing:
                    # 开始绘制旋转矩形的第一阶段 - 创建基础矩形
                    self.drawing = True
                    self.start_point = scene_pos
                    
                    # 创建临时矩形
                    pen = QPen(self.current_color, 2, Qt.SolidLine)
                    self.temp_rect = self.scene.addRect(QRectF(scene_pos, QSizeF(0, 0)), pen)
                    self.temp_rect.setZValue(1)
                    
                    # 初始角度为0
                    self.rotation_angle = 0
                
                elif self.temp_rect and not self.rotation_handle:
                    # 完成基础矩形，进入旋转阶段
                    rect = self.temp_rect.rect()
                    self.rect_center = rect.center()
                    
                    # 创建旋转控制点
                    handle_size = 8
                    self.rotation_handle = self.scene.addEllipse(
                        QRectF(scene_pos.x() - handle_size/2, 
                              scene_pos.y() - handle_size/2, 
                              handle_size, handle_size),
                        QPen(Qt.blue), QBrush(Qt.blue)
                    )
                    self.rotation_handle.setZValue(2)
                    
                    # 创建旋转控制线
                    self.rotation_line = self.scene.addLine(
                        self.rect_center.x(), self.rect_center.y(),
                        scene_pos.x(), scene_pos.y(),
                        QPen(Qt.blue, 1, Qt.DashLine)
                    )
                    self.rotation_line.setZValue(2)
                
                elif self.rotation_handle:
                    # 完成旋转矩形
                    self._complete_rotated_rectangle()
                    
                    # 重置状态
                    self.drawing = False
                    self.temp_rect = None
                    self.rotation_handle = None
                    self.rotation_line = None
                    self.rect_center = None
        
        elif self.current_tool == "point":
            if event.button() == Qt.LeftButton:
                # 添加点标注
                point_size = 8
                
                # 创建点
                pen = QPen(self.current_color, 2)
                brush = QBrush(self.current_color)
                point_item = self.scene.addEllipse(
                    QRectF(scene_pos.x() - point_size/2, 
                           scene_pos.y() - point_size/2, 
                           point_size, point_size),
                    pen, brush
                )
                point_item.setZValue(1)
                
                # 保存标注
                annotation = {
                    "type": "point",
                    "x": scene_pos.x(),
                    "y": scene_pos.y(),
                    "label": self.current_class,
                    "color": self.current_color.name()
                }
                
                self.annotations.append(annotation)
                self.annotation_items.append(point_item)
                
                # 发送标注变更信号
                self.annotation_changed.emit()
        
        elif self.current_tool == "smart_segment":
            scene_pos = self.mapToScene(event.pos())
            
            # 左键添加前景点，右键添加背景点
            if event.button() == Qt.LeftButton:
                # 添加前景点 (标签 = 1)
                self.segmentation_points.append((scene_pos.x(), scene_pos.y()))
                self.segmentation_labels.append(1)
                
                # 绘制前景点标记 (绿色)
                point_size = 6
                pen = QPen(QColor(0, 255, 0), 2)
                brush = QBrush(QColor(0, 255, 0))
                point_item = self.scene.addEllipse(
                    QRectF(scene_pos.x() - point_size/2, 
                           scene_pos.y() - point_size/2, 
                           point_size, point_size),
                    pen, brush
                )
                point_item.setZValue(2)
                
            elif event.button() == Qt.RightButton:
                # 添加背景点 (标签 = 0)
                self.segmentation_points.append((scene_pos.x(), scene_pos.y()))
                self.segmentation_labels.append(0)
                
                # 绘制背景点标记 (红色)
                point_size = 6
                pen = QPen(QColor(255, 0, 0), 2)
                brush = QBrush(QColor(255, 0, 0))
                point_item = self.scene.addEllipse(
                    QRectF(scene_pos.x() - point_size/2, 
                           scene_pos.y() - point_size/2, 
                           point_size, point_size),
                    pen, brush
                )
                point_item.setZValue(2)
            
            # 如果有至少2个点 (至少1个前景和1个背景)，按中键执行分割
            elif event.button() == Qt.MiddleButton:
                self._execute_smart_segmentation()

    def mouseMoveEvent(self, event):
        """
        鼠标移动事件
        
        Args:
            event (QMouseEvent): 鼠标事件
        """
        if self.image_item is None:
            return super().mouseMoveEvent(event)
        
        # 获取场景坐标
        scene_pos = self.mapToScene(event.pos())
        
        # 根据当前工具处理
        if self.current_tool == "select":
            super().mouseMoveEvent(event)
        
        elif self.current_tool == "rectangle" and self.drawing and self.start_point:
            # 更新矩形大小
            rect = QRectF(
                min(self.start_point.x(), scene_pos.x()),
                min(self.start_point.y(), scene_pos.y()),
                abs(scene_pos.x() - self.start_point.x()),
                abs(scene_pos.y() - self.start_point.y())
            )
            
            if self.current_item:
                self.current_item.setRect(rect)
        
        elif self.current_tool == "polygon" and self.drawing:
            # 更新多边形预览
            if self.temp_points and self.current_item:
                # 创建临时点列表，包含所有点和当前鼠标位置
                temp_preview = self.temp_points + [scene_pos]
                
                # 更新多边形
                pen = QPen(self.current_color, 2, Qt.SolidLine)
                polygon = QPolygonF(temp_preview)
                
                # 移除旧的多边形并创建新的
                if self.current_item:
                    self.scene.removeItem(self.current_item)
                
                self.current_item = self.scene.addPolygon(polygon, pen)
                self.current_item.setZValue(1)
        
        elif self.current_tool == "rotated_rectangle" and self.drawing:
            if self.temp_rect and not self.rotation_handle:
                # 更新临时矩形大小
                rect = QRectF(
                    min(self.start_point.x(), scene_pos.x()),
                    min(self.start_point.y(), scene_pos.y()),
                    abs(scene_pos.x() - self.start_point.x()),
                    abs(scene_pos.y() - self.start_point.y())
                )
                self.temp_rect.setRect(rect)
            
            elif self.rotation_handle and self.rect_center:
                # 更新旋转控制点位置
                handle_size = 8
                self.rotation_handle.setRect(
                    QRectF(scene_pos.x() - handle_size/2, 
                          scene_pos.y() - handle_size/2, 
                          handle_size, handle_size)
                )
                
                # 更新旋转控制线
                self.rotation_line.setLine(
                    self.rect_center.x(), self.rect_center.y(),
                    scene_pos.x(), scene_pos.y()
                )
                
                # 计算旋转角度
                dx = scene_pos.x() - self.rect_center.x()
                dy = scene_pos.y() - self.rect_center.y()
                self.rotation_angle = math.degrees(math.atan2(dy, dx))
                
                # 旋转矩形
                if self.temp_rect:
                    # 保存当前矩形的大小
                    rect = self.temp_rect.rect()
                    
                    # 移除当前矩形
                    self.scene.removeItem(self.temp_rect)
                    
                    # 创建一个新的QGraphicsRectItem
                    pen = QPen(self.current_color, 2, Qt.SolidLine)
                    self.temp_rect = self.scene.addRect(rect, pen)
                    
                    # 创建变换矩阵来旋转矩形
                    transform = QTransform()
                    transform.translate(self.rect_center.x(), self.rect_center.y())
                    transform.rotate(self.rotation_angle)
                    transform.translate(-self.rect_center.x(), -self.rect_center.y())
                    
                    # 应用变换
                    self.temp_rect.setTransform(transform)
                    self.temp_rect.setZValue(1)
    
    def mouseReleaseEvent(self, event):
        """
        鼠标释放事件
        
        Args:
            event (QMouseEvent): 鼠标事件
        """
        if self.image_item is None:
            return super().mouseReleaseEvent(event)
        
        # 获取场景坐标
        scene_pos = self.mapToScene(event.pos())
        
        # 根据当前工具处理
        if self.current_tool == "select":
            super().mouseReleaseEvent(event)
        
        elif self.current_tool == "rectangle" and self.drawing:
            if event.button() == Qt.LeftButton and self.start_point:
                # 完成矩形
                if self.current_item:
                    rect = self.current_item.rect()
                    
                    # 确保矩形有尺寸
                    if rect.width() > 5 and rect.height() > 5:
                        # 保存标注
                        annotation = {
                            "type": "rectangle",
                            "x": rect.x(),
                            "y": rect.y(),
                            "width": rect.width(),
                            "height": rect.height(),
                            "label": self.current_class,
                            "color": self.current_color.name()
                        }
                        
                        self.annotations.append(annotation)
                        self.annotation_items.append(self.current_item)
                        
                        # 发送标注变更信号
                        self.annotation_changed.emit()
                    else:
                        # 如果矩形太小，删除它
                        self.scene.removeItem(self.current_item)
                
                # 重置状态
                self.drawing = False
                self.start_point = None
                self.current_item = None
        
        elif self.current_tool == "polygon" and self.drawing:
            if event.button() == Qt.RightButton and len(self.temp_points) >= 3:
                # 完成多边形
                self._complete_polygon()
            
            # 重置状态
            self.drawing = False
            self.temp_points = []
            self.current_item = None
        
        elif self.current_tool == "rotated_rectangle" and self.drawing:
            if self.rotation_handle:
                # 完成旋转矩形
                self._complete_rotated_rectangle()
                
                # 重置状态
                self.drawing = False
                self.temp_rect = None
                self.rotation_handle = None
                self.rotation_line = None
                self.rect_center = None
        
        elif self.current_tool == "point":
            if event.button() == Qt.LeftButton:
                # 添加点标注
                point_size = 8
                
                # 创建点
                pen = QPen(self.current_color, 2)
                brush = QBrush(self.current_color)
                point_item = self.scene.addEllipse(
                    QRectF(scene_pos.x() - point_size/2, 
                           scene_pos.y() - point_size/2, 
                           point_size, point_size),
                    pen, brush
                )
                point_item.setZValue(1)
                
                # 保存标注
                annotation = {
                    "type": "point",
                    "x": scene_pos.x(),
                    "y": scene_pos.y(),
                    "label": self.current_class,
                    "color": self.current_color.name()
                }
                
                self.annotations.append(annotation)
                self.annotation_items.append(point_item)
                
                # 发送标注变更信号
                self.annotation_changed.emit()
        
        elif self.current_tool == "smart_segment":
            # 智能分割逻辑将在后续实现
            pass

    def _complete_polygon(self):
        """完成多边形绘制"""
        if len(self.temp_points) >= 3:
            # 创建多边形路径
            polygon = QPolygonF(self.temp_points)
            
            # 创建多边形图形项
            pen = QPen(self.current_color, 2, Qt.SolidLine)
            brush = QBrush(self.current_color, Qt.SolidPattern)
            brush.setColor(QColor(self.current_color).lighter(150))
            
            # 移除旧的多边形并创建新的
            if self.current_item:
                self.scene.removeItem(self.current_item)
            
            polygon_item = self.scene.addPolygon(polygon, pen, brush)
            polygon_item.setZValue(1)
            
            # 保存标注
            points = []
            for point in self.temp_points:
                points.append({"x": point.x(), "y": point.y()})
            
            annotation = {
                "type": "polygon",
                "points": points,
                "label": self.current_class,
                "color": self.current_color.name()
            }
            
            self.annotations.append(annotation)
            self.annotation_items.append(polygon_item)
            
            # 发送标注变更信号
            self.annotation_changed.emit()
    
    def _complete_rotated_rectangle(self):
        """完成旋转矩形绘制"""
        if self.temp_rect and self.rect_center is not None:
            # 获取原始矩形
            rect = self.temp_rect.rect()
            
            # 计算旋转后的四个角点
            transform = QTransform()
            transform.translate(self.rect_center.x(), self.rect_center.y())
            transform.rotate(self.rotation_angle)
            transform.translate(-self.rect_center.x(), -self.rect_center.y())
            
            # 计算矩形的四个角点
            tl = transform.map(QPointF(rect.topLeft()))
            tr = transform.map(QPointF(rect.topRight()))
            bl = transform.map(QPointF(rect.bottomLeft()))
            br = transform.map(QPointF(rect.bottomRight()))
            
            # 创建多边形
            polygon = QPolygonF([tl, tr, br, bl])
            
            # 创建多边形图形项
            pen = QPen(self.current_color, 2, Qt.SolidLine)
            brush = QBrush(self.current_color, Qt.SolidPattern)
            brush.setColor(QColor(self.current_color).lighter(150))
            
            polygon_item = self.scene.addPolygon(polygon, pen, brush)
            polygon_item.setZValue(1)
            
            # 保存标注
            points = [
                {"x": tl.x(), "y": tl.y()},
                {"x": tr.x(), "y": tr.y()},
                {"x": br.x(), "y": br.y()},
                {"x": bl.x(), "y": bl.y()}
            ]
            
            annotation = {
                "type": "rotated_rectangle",
                "center_x": self.rect_center.x(),
                "center_y": self.rect_center.y(),
                "width": rect.width(),
                "height": rect.height(),
                "angle": self.rotation_angle,
                "points": points,  # 保存计算后的点，方便显示
                "label": self.current_class,
                "color": self.current_color.name()
            }
            
            self.annotations.append(annotation)
            self.annotation_items.append(polygon_item)
            
            # 清理临时对象
            if self.temp_rect:
                self.scene.removeItem(self.temp_rect)
            if self.rotation_handle:
                self.scene.removeItem(self.rotation_handle)
            if self.rotation_line:
                self.scene.removeItem(self.rotation_line)
            
            # 发送标注变更信号
            self.annotation_changed.emit()

    def set_roi(self, roi):
        """
        设置ROI区域
        
        Args:
            roi (QRectF): ROI区域, 相对坐标(0-1)
        """
        # 保存ROI
        self.roi = roi
        
        # 如果没有图像，直接返回
        if not self.image_item:
            return
        
        # 清除之前的ROI显示（如果有）
        if self.roi_item:
            self.scene.removeItem(self.roi_item)
            self.roi_item = None
        
        # 获取图像尺寸
        img_rect = self.image_item.boundingRect()
        width = img_rect.width()
        height = img_rect.height()
        
        # 计算ROI的像素坐标
        roi_rect = QRectF(
            self.roi.x() * width,
            self.roi.y() * height,
            self.roi.width() * width,
            self.roi.height() * height
        )
        
        # 创建ROI显示项
        self.roi_item = QGraphicsRectItem(roi_rect)
        pen = QPen(QColor(0, 255, 0))  # 绿色
        pen.setWidth(2)
        pen.setStyle(Qt.DashLine)
        self.roi_item.setPen(pen)
        
        # 半透明填充
        brush = QBrush(QColor(0, 255, 0, 30))  # 绿色带透明度
        self.roi_item.setBrush(brush)
        
        # 添加到场景
        self.scene.addItem(self.roi_item)
        self.roi_item.setZValue(-0.5)  # 确保在图像上方，标注下方
        self.roi_item.setVisible(self.roi_visible)

    def toggle_roi_visibility(self):
        """切换ROI显示状态"""
        self.roi_visible = not self.roi_visible
        if self.roi_item:
            self.roi_item.setVisible(self.roi_visible)

    def get_roi_image(self):
        """
        获取ROI区域内的图像
        
        Returns:
            numpy.ndarray: ROI区域内的图像，失败返回None
        """
        if self.original_image is None:
            return None
        
        # 获取图像尺寸
        height, width = self.original_image.shape[:2]
        
        # 计算ROI的像素坐标
        x = int(self.roi.x() * width)
        y = int(self.roi.y() * height)
        w = int(self.roi.width() * width)
        h = int(self.roi.height() * height)
        
        # 确保坐标有效
        x = max(0, min(x, width - 1))
        y = max(0, min(y, height - 1))
        w = max(1, min(w, width - x))
        h = max(1, min(h, height - y))
        
        # 截取ROI区域
        roi_image = self.original_image[y:y+h, x:x+w].copy()
        
        return roi_image

    def _execute_smart_segmentation(self):
        """执行智能分割"""
        # 检查是否有足够的点
        if not self.segmentation_points or len(self.segmentation_points) < 2:
            return
        
        # 检查是否同时有前景和背景点
        if 1 not in self.segmentation_labels or 0 not in self.segmentation_labels:
            return
        
        # 获取当前图像
        if not self.image_item or not self.image_path:
            return
        
        # 执行交互式分割
        try:
            mask, polygons = self.segmentation.interactive_segment(
                self.image_path, 
                self.segmentation_points,
                self.segmentation_labels
            )
            
            # 如果没有找到多边形，返回
            if not polygons:
                return
            
            # 显示找到的多边形
            for points in polygons:
                # 创建QPolygonF
                polygon_points = [QPointF(p["x"], p["y"]) for p in points]
                polygon = QPolygonF(polygon_points)
                
                # 创建多边形图形项
                pen = QPen(self.current_color, 2, Qt.SolidLine)
                brush = QBrush(self.current_color)
                brush.setColor(QColor(self.current_color).lighter(150))
                
                polygon_item = self.scene.addPolygon(polygon, pen, brush)
                polygon_item.setZValue(1)
                
                # 保存标注
                annotation = {
                    "type": "polygon",
                    "points": points,
                    "label": self.current_class,
                    "color": self.current_color.name()
                }
                
                self.annotations.append(annotation)
                self.annotation_items.append(polygon_item)
            
            # 清除分割点
            self.segmentation_points = []
            self.segmentation_labels = []
            
            # 刷新场景
            self.scene.update()
            
            # 发送标注变更信号
            self.annotation_changed.emit()
            
        except Exception as e:
            print(f"分割错误: {e}")
            return 